let websocket = null
let host = null

const CHECK_COMMAND = [4, 0, 0, 0, 0, 0, 0, 0]

onmessage = e => {
    if (host === null) {
        //创建websocket连接
        host = e.data
        getWebSocket(host)
    }
    else {
        websocket.send(getUint8Array(e.data))
    }
}

function getWebSocket(host) {
    websocket = new WebSocket( 'ws://' + host + 'message/client')
    websocket.onopen = () => {
        websocket.send(getUint8Array(CHECK_COMMAND))
    }
    websocket.onmessage = (e) => {
        postMessage(e.data)
    }
    websocket.onclose = () => {
        if (websocket.readyState === WebSocket.CLOSED) {
            getWebSocket(host)
        }
    }
    websocket.onerror = () => {
        if (websocket.readyState === WebSocket.CLOSED) {
            getWebSocket(host)
        }
    }
}

function getUint8Array(arr) {
    let command = new Uint8Array(arr.length)
    for (let i = 0; i < arr.length; i++){
        command[i] = arr[i]
    }
    return command
}